<template>
    <a-layout-sider collapsible :width="280" :collapsed-width="64" v-model:collapsed="collapsed"
        class="knowledge-sidebar">
        <div class="sidebar-header">
            <span v-if="!collapsed">
                <a-button type="text" size="mini" danger @click="emit('select', undefined, undefined)" style="padding: 0;">
                    <span style="font-size: 16px;">知识库目录</span>
                </a-button>
            </span>
            <a-button type="text" @click="showAddSubModal(1, '/主文件夹', '/主文件夹')">
                <template #icon><icon-plus /></template>
            </a-button>
        </div>

        <a-tree :data="treeData" :field-names="{ key: 'id', title: 'fileName' }" :show-icon="true" block-node
            @select="handleSelect">
            <template #extra="data">
                <div class="tree-node">
                    <!-- <span>{{ data.fileName }}</span> -->
                    <a-button type="text" size="mini" @click.stop="showEditModal(data)">
                        <template #icon><icon-edit /></template>
                    </a-button>
                    <a-popconfirm content="确认删除该节点？" @ok="handleDelete(data.id, data.physicalPath, data.isFolder)">
                        <a-button type="text" size="mini" danger @click.stop>
                            <template #icon><icon-delete /></template>
                        </a-button>
                    </a-popconfirm>
                    <a-button v-if="!collapsed" type="text" size="mini"
                        @click.stop="showAddSubModal(data.id, data.physicalPath, data.logicalPath)">
                        <template #icon><icon-plus /></template>
                    </a-button>
                </div>
            </template>
            <!-- <template #icon="{ isFolder }">
                <icon-folder v-if="isFolder" />
                <icon-file v-else />
            </template> -->
        </a-tree>
    </a-layout-sider>
    <a-modal v-model:visible="modalVisible" title="新建子文件夹" @ok="handleSubmit">
        <a-form :model="form">
            <a-form-item label="文件夹名称" field="name">
                <a-input v-model="form.fileName" placeholder="请输入名称" />
            </a-form-item>
        </a-form>
    </a-modal>
    <a-modal v-model:visible="editModalVisible" :title="`修改 ${currentNode.fileName}`" @ok="handleUpdate">
        <a-form :model="editForm">
            <a-form-item label="名称" field="fileName">
                <a-input v-model="editForm.fileName" />
            </a-form-item>
        </a-form>
    </a-modal>
</template>

<script setup lang="ts">
import { ref, nextTick } from 'vue'
import { addFolder, listKnowledge, deleteKnowledge, updateKnowledge } from '@/apis/knowledge/knowledge'

const emit = defineEmits(['select', 'create-folder'])
const collapsed = ref(false)
const treeData = ref([])
const modalVisible = ref(false)
const currentParentId = ref<number>()
const currentPhysicalPath = ref<string>()
const currentLogicalPath = ref<string>()
const editModalVisible = ref(false)
const currentNode = ref<any>({})
const editForm = reactive({
    fileName: ''
})
const form = reactive({
    fileName: ''
})

const showEditModal = (nodeData: any) => {
    currentNode.value = nodeData
    editForm.fileName = nodeData.fileName
    editModalVisible.value = true
}

// 处理更新
const handleUpdate = async () => {
    try {
        await updateKnowledge({
            id: currentNode.value.id,
            fileName: editForm.fileName,
            physicalPath: currentNode.value.physicalPath
        })
        await loadTreeData()
        editModalVisible.value = false
    } catch (e) {
        console.error('更新失败:', e)
    }
}

// 处理删除
const handleDelete = async (id: string, physicalPath: string, isFolder: boolean) => {
    try {
        await deleteKnowledge(id, physicalPath, isFolder)
        await loadTreeData()
    } catch (e) {
        console.error('删除失败:', e)
    }
}

const showAddSubModal = (parentId: number, physicalPath, logicalPath) => {
    currentParentId.value = parentId
    currentPhysicalPath.value = physicalPath,
        currentLogicalPath.value = logicalPath
    modalVisible.value = true
}

const handleSubmit = async () => {
    try {
        await addFolder({
            fileName: form.fileName,
            parentFolderId: currentParentId.value,
            physicalPath: currentLogicalPath.value,
            logicalPath: currentLogicalPath.value,
            createUser: 1
        })

        // 刷新数据 ✅ 网页11
        await loadTreeData()
        modalVisible.value = false
        form.fileName = ''
    } catch (e) {
        console.error('创建失败:', e)
    }
}

const loadTreeData = async () => {
    const res = await listKnowledge({
        isFolder: true,
        fileName: undefined,
        physicalPath: undefined,
        logicalPath: undefined,
        fileType: undefined,
        createdBy: undefined,
        createdAt: undefined,
        updatedAt: undefined,
        createUser: undefined,
        createTime: undefined,
        sort: [],
        page: 1,
        size: 100
    })
    treeData.value = buildTree(res.data.list)
}

// 构建树形结构
const buildTree = (data: any[], parentId = 1) => {
    return data
        .filter(item => item.parentFolderId === parentId)
        .map(item => ({
            ...item,
            children: buildTree(data, item.id)
        }))
}

// 处理目录选择
// const handleSelect = (selectedKeys: string[]) => {
//     emit('select', selectedKeys[0])
// }

const handleSelect = (selectedKeys: string[], extra: { selected: boolean, selectedNodes: TreeNodeData[] }) => {
    const node = extra.selectedNodes[0]
    emit('select', node.id, node.physicalPath) // 新增第二个参数
}

// 初始化加载
loadTreeData()
</script>

<style scoped>
.knowledge-sidebar {
    height: 100vh;
    border-right: 1px solid var(--color-border);
}

.sidebar-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px;
    border-bottom: 1px solid var(--color-border);
}
</style>
